import { Tools } from "../../common/Tools";
import { AudioManager1 } from "../../manager/AudioManager1";
import LevelPre_14 from "./LevelPre_14";
import LvItem from "../../LvItem";
import { BUNDLE_TYPE_ENUM, EVENT_NAME_ENUM } from "../../base/EnumIndex";
import { ResManager1 } from "../../manager/ResManager1";
import { EventManager } from "../../manager/EventManager";
const { ccclass, property } = cc._decorator;

@ccclass
export default class LvItem_14 extends cc.Component {
    /** 是否可点击  Bool */
    isClick: boolean = false;
    /** 配置信息 */
    config: any = null;
    /** 关卡总类 */
    levelBase: LevelPre_14 = null;
    /** 是否是下方可拖动的节点 */
    @property(cc.Boolean)
    isDownItem: boolean = true;

    /** 背景图片 和 物品图片一样*/
    itemBg: cc.Node = null;
    /** 物品图片 */
    itemSpr: cc.Node = null;

    initPos: cc.Vec3 = null;    //初始化坐标
    onLoad() {
        this.node.addComponent(cc.BlockInputEvents);
    }
    start() {
    }
    touchStartPos: cc.Vec3 = null;
    isTouchMove: boolean = false;
    async initItem(config: any, levelBase: LevelPre_14) {
        this.config = config;
        this.levelBase = levelBase;

        if (this.isDownItem) {
            this.itemBg = this.node.getChildByName("itemBg");
            this.itemSpr = this.node.getChildByName("itemSpr");
        } else {
            cc.log("initItem14", this.node.name);
            this.itemSpr = this.node;
        }

        this.initPos = cc.v3(this.node.position);

        this.itemSpr.on(cc.Node.EventType.TOUCH_START, this.touchStartBack, this);
        if (this.configIsTouchMove) {
            this.itemSpr.on(cc.Node.EventType.TOUCH_MOVE, this.touchMoveBack, this);
        }
        this.itemSpr.on(cc.Node.EventType.TOUCH_END, this.touchMoveEndBack, this);
        this.itemSpr.on(cc.Node.EventType.TOUCH_CANCEL, this.touchMoveEndBack, this);

        if (this.isDownItem) {
            let itemSpr = await ResManager1.ins.loadRes("spr/" + this.config.sprUrl, cc.SpriteFrame, BUNDLE_TYPE_ENUM.LEVEL);
            Tools.setSpriteFrame(this.itemBg, itemSpr);
            Tools.setSpriteFrame(this.itemSpr, itemSpr);

            if (this.config.info) {
                this.node.getChildByName("itemLab").getComponent(cc.Label).string = this.config.info;
            }
            if (this.levelBase.interJson["showItemLab"]) {
                this.node.getChildByName("itemLab").active = true;
            }
        }

        this.isClick = true;
    }
    /** 触摸开始回调 */
    touchStartBack(event: cc.Event.EventTouch) {
        cc.log("touchStartBack", this.isClick, this.isDownItem)
        if (!this.isClick) { return; }
        this.touchStartPos = cc.v3(event.getLocation());
        this.isTouchMove = false;

        if (!this.isDownItem) { return; }
        // Tools.setNodeParent(event.target as cc.Node, this.levelBase.viewBg);
        Tools.setNodeParent(event.target as cc.Node, cc.find('Canvas'));
    };
    /** 触摸移动回调 */
    touchMoveBack(event: cc.Event.EventTouch) {
        if (!this.isClick) { return; }
        // if (!this.touchStartPos || Tools.getDistance(this.touchStartPos, event.getLocation()) <= TOUCH_MOVE_LEN) { return; }
        if (!this.touchStartPos) { return; }
        this.isTouchMove = true;

        let node = event.target as cc.Node;
        // let moveScale = node.scale / this.getWorldScale(node.scale, node);
        // node.position = node.position.add(cc.v3(event.getDelta().multiplyScalar(moveScale)));

        let location = event.getLocation();
        let pos = Tools.getToNodePosForWorld(location, node.parent);
        node.setPosition(pos);
    };
    /** 触摸移动结束回调 */
    touchMoveEndBack(event: cc.Event.EventTouch) {
        if (!this.isClick) { return; }
        // if (!this.isTouchMove && !this.clickConfig) {
        //     return; 
        // }      
        this.runInterNode(false);
    };

    /** 执行碰撞的检测    是都正在拖动中 */
    runInterNode(isMove: boolean = false) {
        let inter = this.getRunInterTween(isMove);
        if (!isMove && this.clickConfig && !this.isTouchMove) {
            inter = this.clickConfig;
        }
        if (inter) {
            if (inter.interTween) {
                if (typeof inter.interTween == "string") {
                    this.runJsonTween(inter.interTween);
                } else {
                    this.levelBase.runNodeTween(this.levelBase.viewBg, inter.interTween);
                }
            }
            if (inter.addState && inter.addState.length > 0) {
                let addArr = this.levelBase.addHaveStates(inter.addState);
                this.runStateTween(addArr);
                //播放正确音效
                if (this.levelBase.interJson.correctAudio) {
                    AudioManager1.playAudio("xuandui", 1, BUNDLE_TYPE_ENUM.GAME);
                }
            }
            if (inter.removeState) {
                let removeArr = this.levelBase.removeStates(inter.removeState);
                this.runStateTween(removeArr, "remove_");
            }
            this.returnInitPos(false);
        } else if (!isMove) {
            if (this.levelBase.interJson.totalStep && this.config["cuowuJianNum"]) {
                EventManager.ins.emit(EVENT_NAME_ENUM.FINISH_INTER_TWEEN, "TcStep");
                if (this.levelBase.interJson.errorAudio) {
                    AudioManager1.playAudio("cuowu", 1, BUNDLE_TYPE_ENUM.GAME);
                }
            }
            this.returnInitPos();
        }
    };

    /** 获取要执行的交互Tween */
    getRunInterTween(isMove: boolean) {
        for (let i = 0; i < this.config.interArr.length; i++) {
            let tempData = this.config.interArr[i];
            //@ts-ignore
            let node = this.levelBase.getChildForName(isMove ? tempData.moveNode : tempData.interNode);
            if (!node) { continue; }
            if (this.isNodeInterNode(node, this.itemSpr) &&
                this.levelBase.isHaveStates(tempData.haveState)
                && this.levelBase.isHaveNoStates(tempData.haveNoState)) {
                return tempData;
            };
        }
        return null;
    };
    /** 返回原来的位置 */
    returnInitPos(isMove: boolean = true) {
        if (!this.isDownItem) {
            if (this.config.isReturn && isMove) {
                let lvItem = this.node.getComponent(LvItem);
                this.itemSpr.position = lvItem.initPos;
            }
            return;
        }
        if (!isMove) {
            // if( !this.isDownItem ){
            //     this.node.position = this.initPos;
            //     return;
            // }
            Tools.setNodeParent(this.itemSpr, this.node);
            this.itemSpr.position = cc.v3(this.itemBg.position);
            return;
        }
        if (this.levelBase.interJson.errorAudio) {
            AudioManager1.playAudio("cuowu", 1, BUNDLE_TYPE_ENUM.GAME);
        }
        let toPos = !this.isDownItem ? this.initPos : cc.v3(Tools.getToNodePosForNode(this.itemBg, this.itemSpr.parent));
        this.isClick = false;
        cc.tween(this.itemSpr)
            .to(0.1, { position: toPos })
            .call(() => {
                if (this.isDownItem) {
                    Tools.setNodeParent(this.itemSpr, this.node);
                }
                this.isClick = true;
            }).start();
    };
    /** 执行数组状态的Tween */
    runStateTween(states: Array<string>, tempStr: string = "add_") {
        for (let i = 0; i < states.length; i++) {
            this.runJsonTween(tempStr + states[i]);
        }
    };
    /** 执行某个Json配置的InterTween */
    runJsonTween(tweenName: string) {
        let tweenInfo = this.levelBase.getInterTwForName(tweenName);
        if (tweenInfo) {
            this.levelBase.runNodeTween(this.levelBase.viewBg, tweenInfo.interTween);
        }
    };


    // /** 获取生成下方时的 大小 */
    get downItmeScale() {
        let tempWidth = Math.max(this.itemSpr.width, this.itemSpr.height);
        let toScale = 130 / tempWidth;
        return toScale;
    }

    /** 获取点击得Tween */
    get clickConfig() {
        for (let i = 0; i < this.config.interArr.length; i++) {
            let tempData = this.config.interArr[i];
            //@ts-ignore
            if (this.config.interArr[i].click && this.levelBase.isHaveStates(tempData.haveState)) {
                return this.config.interArr[i];
            }
        }
        return null;
    };

    /** 本物品是否有 拖动事件 */
    get configIsTouchMove() {
        for (let i = 0; i < this.config.interArr.length; i++) {
            if (this.config.interArr[i].moveNode || this.config.interArr[i].interNode) {
                return true;
            }
        }
        return false;
    };

    protected onEnable(): void {
    }


    /** 判断两个节点是否相交 */
    isNodeInterNode(node1: cc.Node, node2: cc.Node) {
        if (!node1.active || !node2.active || !node1.parent.active || !node2.parent.active) { return false; };
        let wordPos1 = Tools.getToWorldPosAR(node1);
        let worldScale1 = this.getWorldScale(node1.scale, node1);
        let wordPos2 = Tools.getToWorldPosAR(node2);
        let worldScale2 = this.getWorldScale(node2.scale, node2);
        let size1 = cc.size(node1.width * worldScale1, node1.height * worldScale1);
        let size2 = cc.size(node2.width * worldScale2, node2.height * worldScale2);

        let rect1 = new cc.Rect(wordPos1.x - size1.width / 2, wordPos1.y - size1.height / 2, size1.width, size1.height);
        let rect2 = new cc.Rect(wordPos2.x - size2.width / 2, wordPos2.y - size2.height / 2, size2.width, size2.height);
        if (cc.Intersection.rectRect(rect1, rect2)) {
            return true;
        }
        return false;
    };
    /** 获取世界Scale */
    getWorldScale(tempScale: number = 1, node: cc.Node) {
        if (node.parent) {
            return this.getWorldScale(tempScale * node.parent.scale, node.parent);
        }
        return tempScale;
    };
}
